package com.okaixz.client.service.impl;

import com.alibaba.fastjson2.JSON;
import com.okaixz.client.mapper.KbUserAssistantInfoNewMapper;
import com.okaixz.client.model.domain.KbAssistant;
import com.okaixz.client.model.domain.KbCustomerAssistant;
import com.okaixz.client.model.domain.KbUserAssistantInfoNew;
import com.okaixz.client.model.domain.User;
import com.okaixz.client.service.IKbAssistantService;
import com.okaixz.client.service.IKbCustomerAssistantService;
import com.okaixz.client.service.IKbUserAssistantInfoNewService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.okaixz.client.service.IUserService;
import com.okaixz.common.client.exception.BusinessException;
import com.okaixz.common.client.exception.CommonErrorCode;
import com.okaixz.common.constant.CommonConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author cdz
 * @since 2025-11-11
 */
@Service
public class KbUserAssistantInfoNewServiceImpl extends ServiceImpl<KbUserAssistantInfoNewMapper, KbUserAssistantInfoNew> implements IKbUserAssistantInfoNewService {
    @Autowired
    private IKbAssistantService kbAssistantService;
    @Autowired
    private IKbCustomerAssistantService customAssistantService;
    @Autowired
    private IUserService userService;

    @Override
    public List<KbAssistant> getAssistantByUserIdAndSex(String userId, int sex) {
        List<KbAssistant> result = null;
        KbUserAssistantInfoNew one = lambdaQuery()
                .eq(KbUserAssistantInfoNew::getUserId, userId)
                .one();
        String jsonIds = null;
        List<Long> ids =null;
        if (one == null) {
            one = new KbUserAssistantInfoNew();
            one.setUserId(userId);

            result = kbAssistantService.defaultlist(sex);
            ids = result.stream()
                    .map(KbAssistant::getId)
                    .collect(Collectors.toList());
            //将ids转成json串
            jsonIds = JSON.toJSONString(ids);
            if (sex == CommonConstants.SEX_BOY) {
                one.setBoyAssistantIds(jsonIds);
            } else {
                one.setGirlAssistantIds(jsonIds);
            }
            boolean b = saveOrUpdate(one);
            if (!b) {
                throw new BusinessException(CommonErrorCode.OP_FAIL);
            }
            return result;
        } else {
            jsonIds = sex == CommonConstants.SEX_BOY ? one.getBoyAssistantIds() : one.getGirlAssistantIds();
            if(jsonIds!=null){
                ids = JSON.parseArray(jsonIds, Long.class);
            }else {
                result = kbAssistantService.defaultlist(sex);
                ids = result.stream()
                        .map(KbAssistant::getId)
                        .collect(Collectors.toList());
                //将ids转成json串
                jsonIds = JSON.toJSONString(ids);
                if (sex == CommonConstants.SEX_BOY) {
                    one.setBoyAssistantIds(jsonIds);
                } else {
                    one.setGirlAssistantIds(jsonIds);
                }
                boolean b = saveOrUpdate(one);
                if (!b) {
                    throw new BusinessException(CommonErrorCode.OP_FAIL);
                }
                return result;
            }
        }

        if (ids == null || ids.size() == 0) {
            throw new BusinessException(CommonErrorCode.OP_FAIL);
        }

        //查询数据
        return getKbAssistantByIds(ids);
    }
    @Override
    public List<KbAssistant> getAssistantByUserIdAndSex() {
        User user = userService.getTokenUser();
        //查询数据
        return getAssistantByUserIdAndSex(user.getUserId(), user.getSex());
    }

    @Override
    public List<KbAssistant> saveOrUpdateByUserIdAndSex(List<Long> ids, String userId, int sex) {
        //将ids转成json串
        String jsonString = JSON.toJSONString(ids);

        List<KbAssistant> result = null;
        KbUserAssistantInfoNew one = lambdaQuery()
                .eq(KbUserAssistantInfoNew::getUserId, userId)
                .one();
        if (one == null) {
            one = new KbUserAssistantInfoNew();
            one.setUserId(userId);
        }
        if (sex == CommonConstants.SEX_BOY) {
            one.setBoyAssistantIds(jsonString);
        } else {
            one.setGirlAssistantIds(jsonString);
        }
        //保存数据
        boolean b = saveOrUpdate(one);
        if (!b) {
            throw new BusinessException(CommonErrorCode.OP_FAIL);
        }

        //查询数据
        return getKbAssistantByIds(ids);
    }

    @Override
    public List<KbAssistant> saveOrUpdateByUserIdAndSex(List<Long> ids) {
        User user = userService.getTokenUser();
        return saveOrUpdateByUserIdAndSex(ids, user.getUserId(), user.getSex());
    }

    @Override
    public KbAssistant addAssistant(Long id, int type) {
        KbAssistant kbAssistant = null;
        if (CommonConstants.KB_ASSISTANT_TYPE_CUSTOMER == type) {
            KbCustomerAssistant byId = customAssistantService.getById(id);
            kbAssistant = byId.transfornToKbAssistant();
            id=kbAssistant.getId();
        } else {
            kbAssistant = kbAssistantService.getById(id);
        }
        if (kbAssistant == null) {
            throw new BusinessException(CommonErrorCode.ASSISTANT_NOT_EXIST);
        }

        User user = userService.getTokenUser();
        String userId = user.getUserId();
        int sex = user.getSex();
        KbUserAssistantInfoNew one = lambdaQuery()
                .eq(KbUserAssistantInfoNew::getUserId, userId)
                .one();
        if (one == null) {
            throw new BusinessException(CommonErrorCode.OP_FAIL);
        }
        String jsonIds = sex == CommonConstants.SEX_BOY ? one.getBoyAssistantIds() : one.getGirlAssistantIds();
        if (jsonIds == null) {
            throw new BusinessException(CommonErrorCode.OP_FAIL);
        }
        List<Long> ids = JSON.parseArray(jsonIds, Long.class);
        ids.add(0,id);
        String jsonString = JSON.toJSONString(ids);
        if (sex == CommonConstants.SEX_BOY) {
            one.setBoyAssistantIds(jsonString);
        } else {
            one.setGirlAssistantIds(jsonString);
        }
        boolean b = saveOrUpdate(one);
        if (!b) {
            throw new BusinessException(CommonErrorCode.OP_FAIL);
        }
        return kbAssistant;
    }

    @Override
    public List<KbAssistant> getKbAssistantByIds(List<Long> ids) {
        if (ids == null || ids.size() == 0) {
            return null;
        }
        List<KbAssistant> result = null;

        List<Long> systemIds = new ArrayList<>();
        List<Long> customerIds = new ArrayList<>();

        ids.stream()
                .forEach(item -> {
                    if (item.longValue() > CommonConstants.SYSTEM_ASSISTANT_OFFSET) {
                        customerIds.add(item - CommonConstants.SYSTEM_ASSISTANT_OFFSET);
                    } else {
                        systemIds.add(item);
                    }
                });
        if (customerIds.size() == 0) {
            //没有自定义标签 全是系统标签
            Collection<KbAssistant> kbAssistants = kbAssistantService.listByIds(ids);
            if (kbAssistants != null) {
                result = new ArrayList<>(kbAssistants);
            }
            return result;
        }
        result = new ArrayList<>();

        //查询自定义标签
        Collection<KbCustomerAssistant> kbCustomerAssistants = customAssistantService.listByIds(customerIds);
        //查询系统标签
        Collection<KbAssistant> kbAssistants = kbAssistantService.listByIds(systemIds);
        if (kbCustomerAssistants == null || kbCustomerAssistants.size() == 0) {
            return new ArrayList<>(kbAssistants);
        }

        Map<Long, KbCustomerAssistant> customeList = new HashMap<>();
        Map<Long, KbAssistant> systemList = new HashMap<>();
        if (kbCustomerAssistants != null && kbCustomerAssistants.size() > 0) {
            customeList = kbCustomerAssistants.stream()
                    .collect(Collectors.toMap(KbCustomerAssistant::getId, item -> item));
        }
        if (kbAssistants != null && kbAssistants.size() > 0) {
            systemList = kbAssistants.stream()
                    .collect(Collectors.toMap(KbAssistant::getId, item -> item));
        }


        for (Long id : ids) {
            if (id.longValue() > CommonConstants.SYSTEM_ASSISTANT_OFFSET) {
                //自定义标签
                KbCustomerAssistant customerAssistant = customeList.get(id - CommonConstants.SYSTEM_ASSISTANT_OFFSET);
                if (customerAssistant != null) {
                    KbAssistant kbAssistant = customerAssistant.transfornToKbAssistant();
                    result.add(kbAssistant);
                }
            } else {
                //系统标签
                KbAssistant kbAssistant = systemList.get(id);
                if (kbAssistant != null) {
                    result.add(kbAssistant);
                }
            }
        }

        return result;
    }
}
